import java.io.*;
import java.util.*;

public class FileUpdate2{
  public static void main(String[] args)throws IOException{
    Scanner kbdScanner = new Scanner(System.in);
    // 1. Create a FileInputStream object
    FileInputStream instream = new FileInputStream("names.txt");
    
    // 2. Wrap the input stream in a scanner
    Scanner fscanner = new Scanner(instream);
    
    //3. Count the number of lines in the text-file
    int numLines = 0;
    while(fscanner.hasNextLine()){
        fscanner.nextLine();
        numLines++;
    }
     //4. Reset the scanner  
     fscanner.close();
     instream = new FileInputStream("names.txt");
     fscanner = new Scanner(instream);   
     
    //5. Create an array with numLines elements
    String[] array = new String[numLines];
    
    // 6.  Initialize the array with the file contents
    for(int k = 0; k < array.length; k++)
      array[k] = fscanner.nextLine();
    
    // 7. Close the input stream
    fscanner.close();
    
     // 8. Update the array
     System.out.printf("Enter a new name: ");
     String name = kbdScanner.nextLine();
     System.out.printf("Enter the index of the name to be modified [0 - %d]: ", numLines - 1);
     int index = kbdScanner.nextInt();
     array[index] = new String(name); 
     
     // 9. Create an associated output stream
     PrintWriter pwriter = new PrintWriter("names.txt");
     
     // 10. Overwrite the file with the values of the updated array
     for(int k = 0; k <= array.length - 2; k++)
       pwriter.println(array[k]); 
     
       pwriter.print(array[array.length - 1]);   // Write last element without generating new line
     
     // 11. Close the output stream
     pwriter.close();
     // 12. For convenience inform the user that the file has been updated
     System.out.println("The file names.txt has been updated . . .");
  }
}     